﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Animation;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class MoveAnimationForProjectCardBehavior : Behavior<ProjectCardControl>
    {
        private ContentPresenter _parent;
        private ProjectCardViewModel _projectCardViewModel;
        private Storyboard _storyboardMove;
        private DoubleAnimation _xAnimation;

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _projectCardViewModel = (ProjectCardViewModel)AssociatedObject.DataContext;
                _projectCardViewModel.PropertyChanged += ProjectCardPropertyChanged;

                if (_parent == null)
                {
                    _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
                }

                var duration = new Duration(TimeSpan.FromMilliseconds(400));

                _xAnimation = new DoubleAnimation();

                _xAnimation.Duration = duration;
                
                _storyboardMove = new Storyboard();
                _storyboardMove.Duration = duration;

                _storyboardMove.Children.Add(_xAnimation);

                Storyboard.SetTarget(_xAnimation, _parent);

                Storyboard.SetTargetProperty(_xAnimation, new PropertyPath("(Canvas.Left)"));

        
                MoveCard();
           
            };

        }

        void ProjectCardPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsCardVisibleInCurrentWall" )
            {
                MoveCard();
            }
        }

        private void MoveCard()
        {
            if (_projectCardViewModel.IsCardVisibleInCurrentWall)
            {
                _xAnimation.To = _projectCardViewModel.Position.X;
                _storyboardMove.Begin();
            }
            else
            {
                _xAnimation.To = -250;
                _storyboardMove.Begin();
            }
        }
    }
}
